package base.core.mybatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import lombok.SneakyThrows;

/**
 * Mybatis数组,符串互转
 * <p>
 * MappedJdbcTypes 数据库中的数据类型 MappedTypes java中的的数据类型
 *
 * @author xuzihui
 * @date 2019-11-20
 */
@MappedTypes(value = {String[].class})
public class ArrayStringTypeHandler extends BaseTypeHandler<String[]> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, arrayToString(parameter));
	}

	@Override
	@SneakyThrows
	public String[] getNullableResult(ResultSet rs, String columnName) {
		String reString = rs.getString(columnName);
		return stringToArray(reString);
	}

	@Override
	@SneakyThrows
	public String[] getNullableResult(ResultSet rs, int columnIndex) {
		String reString = rs.getString(columnIndex);
		return stringToArray(reString);
	}

	@Override
	@SneakyThrows
	public String[] getNullableResult(CallableStatement cs, int columnIndex) {
		String reString = cs.getString(columnIndex);
		return stringToArray(reString);
	}

	private static String[] stringToArray(String str) {
		if (!StringUtils.hasText(str)) {
			return null;
		}
		String[] split = str.split(",");
		List<String> collect = Arrays.stream(split).filter(s -> StringUtils.hasText(s)).collect(Collectors.toList());
		return collect.toArray(new String[0]);
	}

	private static String arrayToString(String[] arr) {
		if (arr == null || arr.length == 0) {
			return null;
		}
		return Arrays.stream(arr).filter(s -> StringUtils.hasText(s)).collect(Collectors.joining(",", ",", ","));
	}
}
